package com.sdh.onlinemarket.controller;


import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdh.onlinemarket.common.annotation.AdminToken;
import com.sdh.onlinemarket.common.annotation.UserLoginToken;
import com.sdh.onlinemarket.common.dto.PasswordChangeDTO;
import com.sdh.onlinemarket.common.lang.Result;
import com.sdh.onlinemarket.common.util.TokenService;
import com.sdh.onlinemarket.entity.User;
import com.sdh.onlinemarket.entity.Usersecure;
import com.sdh.onlinemarket.service.UserService;
import com.sdh.onlinemarket.service.UsersecureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 施德昊
 * @since 2021-10-27
 */
@Api(tags = "账户相关模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    UsersecureService usersecureService;
    @Autowired
    TokenService tokenService;

    @UserLoginToken
    @ApiOperation(value = "获取当前用户信息")
    @PostMapping("/getuserbyid")
    public Result getUserId(HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        User user = userService.getOne(new QueryWrapper<User>().eq("userid",userid));
        System.out.println(user);
        System.out.println(LocalDateTime.now());
        return Result.succ("succ",user);
    }

//    @PostMapping("/adduser")
//    @ResponseBody
//    public Result addUser(@RequestBody User user){
//        userService.save(user);
//        return Result.succ("成功");
//    }


    @UserLoginToken
    @ApiOperation(value = "设置当前用户手机号")
    @PostMapping("/setphone")
    @ResponseBody
    public Result setPhone(@RequestBody User user,HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",userid);
        User userTemp = userService.getOne(wrapper);
        /*
        验证手机号
         */
        if(userTemp==null){
            return Result.fail("没有该用户");
        }
        if(user.getPhonenum()==null){
            return Result.fail("没有手机号");
        }
        userTemp.setPhonenum(user.getPhonenum());
        userService.update(userTemp,wrapper);
        return Result.succ("修改手机号成功");
    }

    @UserLoginToken
    @ApiOperation(value = "设置当前用户地址")
    @PostMapping("/setaddr")
    @ResponseBody
    public Result setAddr(@RequestBody User user,HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",userid);
        User userTemp = userService.getOne(wrapper);
        /*
        验证地址
         */
        if(userTemp==null){
            return Result.fail("没有该用户");
        }
        if(user.getAddr()==null){
            return Result.fail("没有地址");
        }
        userTemp.setAddr(user.getAddr());
        userService.update(userTemp,wrapper);
        return Result.succ("修改地址成功");
    }

    @UserLoginToken
    @ApiOperation(value = "设置当前用户邮箱")
    @PostMapping("/setemail")
    @ResponseBody
    public Result setEmail(@RequestBody User user,HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",userid);
        User userTemp = userService.getOne(wrapper);
        /*
        验证地址
         */
        if(userTemp==null){
            return Result.fail("没有该用户");
        }
        if(user.getEmail()==null){
            return Result.fail("没有邮箱");
        }
        userTemp.setEmail(user.getEmail());
        userService.update(userTemp,wrapper);
        return Result.succ("修改邮箱成功");
    }

    @UserLoginToken
    @ApiOperation(value = "设置当前用户姓名身份证")
    @PostMapping("/setnameid")
    @ResponseBody
    public Result setIdNum(@RequestBody User user,HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",userid);
        User userTemp = userService.getOne(wrapper);
        /*
        验证地址
         */
        if(userTemp==null){
            return Result.fail("没有该用户");
        }
        if(user.getIdnum()==null){
            return Result.fail("没有身份证号");
        }
        if(user.getUsername()==null){
            return Result.fail("没有姓名");
        }

        userTemp.setIdnum(user.getIdnum());
        userTemp.setUsername(user.getUsername());
        userService.update(userTemp,wrapper);
        return Result.succ("身份绑定成功");
    }

    @UserLoginToken
    @ApiOperation(value = "修改当前用户密码")
    @PostMapping("/changepassword")
    @ResponseBody
    public Result changePassword(@RequestBody PasswordChangeDTO passwordChangeDTO, HttpServletRequest request){
        String userid = JWT.decode(request.getHeader("token")).getAudience().get(0);
        QueryWrapper<Usersecure> wrapper = new QueryWrapper<Usersecure>().eq("account",userid);
        Usersecure usersecureTemp = usersecureService.getOne(wrapper);

        if(usersecureTemp==null){
            return Result.fail("没有该用户");
        }
        if(!usersecureTemp.getPassword().equals(passwordChangeDTO.getOldpassword())){
            return Result.fail("原密码不一致");
        }
        usersecureTemp.setPassword(passwordChangeDTO.getNewpassword());
        usersecureService.update(usersecureTemp,wrapper);
        return Result.succ("成功修改密码,userid="+usersecureTemp.getAccount());
    }

    @ApiOperation(value = "注册新用户")
    @PostMapping("/userregister")
    @ResponseBody
    public Result userRegister(@RequestBody Usersecure usersecure, HttpServletResponse response){
        if(usersecure == null){
            return Result.fail("参数为空");
        }
        if (usersecure.getAccount() == null||usersecure.getPassword() == null){
            return Result.fail("缺少账户或密码");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",usersecure.getAccount());
        User userTemp = userService.getOne(wrapper);
        if(userTemp != null){
            return Result.fail("该用户已被注册");
        }
        User user = new User();
        user.setUserid(usersecure.getAccount());
        usersecure.setAuthority("0");
        usersecureService.save(usersecure);
        userService.save(user);

        String token = tokenService.getToken(usersecure);
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.succ(token);
    }

    @AdminToken
    @ApiOperation(value = "添加新管理员",notes = "需要管理员权限，并且在管理页面进行该添加操作")
    @PostMapping("/adminregister")
    @ResponseBody
    public Result userRegister(@RequestBody Usersecure usersecure){
        if(usersecure == null){
            return Result.fail("参数为空");
        }
        if (usersecure.getAccount() == null||usersecure.getPassword() == null){
            return Result.fail("缺少账户或密码");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("userid",usersecure.getAccount());
        User userTemp = userService.getOne(wrapper);
        if(userTemp != null){
            return Result.fail("该用户已被注册");
        }
        User user = new User();
        user.setUserid(usersecure.getAccount());
        usersecure.setAuthority("1");
        usersecureService.save(usersecure);
        userService.save(user);
        return Result.succ("管理员账户添加成功");
    }

    //列出所有管理员
    @AdminToken
    @ApiOperation(value = "列出所有管理账户")
    @PostMapping("/listadmin")
    @ResponseBody
    public Result listAdmin(){
        List<Usersecure> usersecureList =
                usersecureService.list(new QueryWrapper<Usersecure>()
                        .eq("authority","1"));
        return Result.succ("查询成功",usersecureList);
    }

    //删除管理员账户
    @AdminToken
    @ApiOperation(value = "删除其他管理员账户",notes = "无法删除自身账户")
    @PostMapping("/deleteadmin")
    @ResponseBody
    public Result userRegister(String userid,HttpServletRequest request){
        if (userid == null){
            return Result.fail("参数为空");
        }
        String currentId = JWT.decode(request.getHeader("token")).getAudience().get(0);

        if (userid.equals(currentId)){
            return Result.fail("不允许删除自己的用户");
        }
        Usersecure usersecuretemp = usersecureService.getOne(new QueryWrapper<Usersecure>().eq("account",userid));

        if (!usersecuretemp.getAuthority().equals("1")){
            return Result.fail("操作错误，无法删除user账户");
        }

        userService.remove(new QueryWrapper<User>().eq("userid",userid));
        usersecureService.remove(new QueryWrapper<Usersecure>().eq("account",userid));
        return Result.succ("删除成功");

    }

}
